#include <stdio.h>
#include "input_screen_dev.h"                                               
#include "input_net_dev.h"

extern Input_dev Input_screen_dev;
extern Input_dir current_input_dir;
extern Input_dev Input_net_dev;

void Input_dir_copy(pInput_dir head,int cnt) {
	int ret_dir;
	int i = cnt;
	pInput_dir buf_head = head;
	while(buf_head->next != NULL) {
		buf_head = buf_head->next;
		i++; //维护驱动名字的
	}
	while(cnt--) {
		pInput_dir new_next = (pInput_dir)malloc(sizeof(Input_dir));
		memcpy((void *)new_next,(void *)buf_head,sizeof(Input_screen_dev)); //注意这里不能用头指针，会死循环
		//修改名字
		char *name = (char *)malloc(20);
		sprintf(name,"input_dir_%d",i-cnt);
		new_next->name = name;
		printf("the name %s \n",new_next->name);
		buf_head->next = new_next;
		buf_head = buf_head->next;
	}
	
}

void add_all_input_div_dev() {
	int i;
	//初始化锁，锁是没被锁住的状态
	pthread_mutex_init(&range_rw_mutex,NULL);
	pthread_cond_init(&range_rw_cond, NULL);
	
	pInput_dir head_buf = &current_input_dir;
	char name_buf[2][30] = {"input_screen_dev","input_net_dev"};
	Input_dir_copy(&current_input_dir,2);
	add_to_input_list(&Input_screen_dev);
	add_to_input_list(&Input_net_dev);
	for(i=0;i<2;i++) {
		pInput_dir dir_buf= head_buf->next;
		dir_buf->find_dev(dir_buf,name_buf[i]);
    	dir_buf->init_dev(dir_buf);
		head_buf = head_buf->next;	
	}
}

int judge_range_isfull() {
	if((range_w+1)%BUF_LEN == range_r) {
		return 1;
	}
	return 0;
}

int judge_range_isempty() {
	if(range_w == range_r) {
		return 1;
	}
	return 0;
}

int push_data_to_range(pInput_data data) {
	if(!judge_range_isfull()) {
		pthread_mutex_lock(&range_rw_mutex);
		
		range_buf[range_w] = *data;
		range_w = (range_w+1)%BUF_LEN;
	
		pthread_cond_signal(&range_rw_cond);  
		pthread_mutex_unlock(&range_rw_mutex);
	}else {
		//如果满了
		pthread_mutex_lock(&range_rw_mutex);  
		pthread_cond_wait(&range_rw_cond, &range_rw_mutex);   //会释放range_rw_mutex锁，等待资源唤醒，唤醒又拿到该锁
		
		range_buf[range_w] = *data;
		range_w = (range_w+1)%BUF_LEN;
		
		pthread_mutex_unlock(&range_rw_mutex);
	}
	return 0;
}

int pop_data_to_range(pInput_data data) { //注意这里传的data要本来就有地址指向，不然对空指针符值是错的
	if(!judge_range_isempty()) {
		pthread_mutex_lock(&range_rw_mutex);
		//拿出来保存在参数里面
		*data = range_buf[range_r];
		range_r = (range_r+1)%BUF_LEN;
		
		pthread_cond_signal(&range_rw_cond);  
		pthread_mutex_unlock(&range_rw_mutex);
	}else {
		//如果是空
		pthread_mutex_lock(&range_rw_mutex);  
		pthread_cond_wait(&range_rw_cond, &range_rw_mutex);
		
		*data = range_buf[range_r];
		range_r = (range_r+1)%BUF_LEN;
		
		pthread_mutex_unlock(&range_rw_mutex);
	}
	return 0;
}


